using System;
using Habanero.Base;
using Habanero.Base.Exceptions;

namespace FireStarterModeller.BO
{
    public class PropertyCompulsoryRule : IBusinessObjectRule
    {
        private IBusinessObject _businessObject;
        private readonly string _propertyName;
        public ErrorLevel ErrorLevel { get; private set; }

        public PropertyCompulsoryRule(string propertyName, ErrorLevel errorLevel)
        {
//            if (businessObject == null) throw new ArgumentNullException("businessObject");
            if (propertyName == null) throw new ArgumentNullException("propertyName");
//            _businessObject = businessObject;
            _propertyName = propertyName;
            ErrorLevel = errorLevel;
//            if (!_businessObject.Props.Contains(propertyName))
//            {
//                string errorMessage = string.Format("The property '{0}' does not exist on the BO '{1}'.",
//                                                    propertyName, businessObject.ClassDef.ClassName);
//                throw new HabaneroDeveloperException(errorMessage, errorMessage);
//            }
        }

        public bool IsValid()
        {
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }


        public bool IsValid(IBusinessObject bo)
        {
            _businessObject = bo;
            CheckPropExistsOnBO();
            return bo.Props[_propertyName].Value != null;
        }

        private void CheckPropExistsOnBO()
        {
            if (!_businessObject.Props.Contains(_propertyName))
            {
                string errorMessage = string.Format("The property '{0}' does not exist on the BO '{1}'.",
                                                    _propertyName, _businessObject.ClassDef.ClassName);
                throw new HabaneroDeveloperException(errorMessage, errorMessage);
            }
        }

        public string Name
        {
            get { return "PropertyCompulsoryRule"; }
        }

        public string Message
        {
            get { return string.Format("'{0}.{1}' is a compulsory field and has no value.", _businessObject.ClassDef.ClassName, _propertyName); }
        }

    }
}